//
//  YYMusicPeopleDetailController.swift
//  STMusic
//
//  Created by stoneobs on 2017/6/15.
//  Copyright © 2017年 stoneobs. All rights reserved.
// //**********************音乐人详情***************************

import UIKit

class YYMusicPeopleDetailController: STTableViewController {
    
    var bannerImageView:UIImageView?
    
    var playButton:STButton?
    
    var desLable:STLabel?
    
    var model:YYMusicPeopleModel = YYMusicPeopleModel(){
        
        didSet{
            
        }
    };
    
    var isInfoUpdate:Bool = false;
    var isListUpdate:Bool = false;
    
    var dataSouce:Array<YYTrack> = [];
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.height = SCREEN_HEIGHT - 64;
        self.tableView.separatorStyle = .none;
        self.tableView.backgroundColor = UIColor.white;
        self.view.backgroundColor = .white;
        
       
        self.loadNetworkRequest();
        // Do any additional setup after loading the view.
    }
    func configSubView(){
        self.view.backgroundColor = .white;
        
        let tableHeaderView = UIView.init(frame: .init(x: 0, y: 0, width: SCREEN_WIDTH, height: 40));
        self.title = self.model.nickname;
        weak var weakSelf = self;
        
        self.bannerImageView = UIImageView.init(frame: .init(x: 0, y: 10, width: SCREEN_WIDTH / 2, height:  SCREEN_WIDTH / 2));
        self.bannerImageView?.sd_setImage(with: URL.init(string: (self.model.pimg)!), placeholderImage: BannerImage, options: .retryFailed);
        self.bannerImageView?.contentMode = .scaleAspectFill;
        self.bannerImageView?.centerX = SCREEN_WIDTH / 2;
        self.bannerImageView?.clipsToBounds = true;
        tableHeaderView.addSubview(self.bannerImageView!);
        
        self.playButton = STButton.init(frame: .init(x: 0, y: 0, width: 32, height: 32),
                                        title: "",
                                        titleColor: nil,
                                        titleFont: 0,
                                        cornerRadius: 0,
                                        backgroundColor: .clear,
                                        backgroundImage: nil,
                                        image: UIImage.init(named: ""));
        
        
        self.playButton?.setBackgroundImage(UIImage.init(named: "btn_play"), for: .normal);
        self.playButton?.setBackgroundImage(UIImage.init(named: "btn_pause"), for: .selected);
        self.playButton?.contentHorizontalAlignment = .center;
        self.playButton?.centerX = SCREEN_WIDTH / 2;
        self.playButton?.centerY = (self.bannerImageView?.bottom)! + 40;
        self.playButton?.clicAction = {but in
            
            weakSelf?.playButton?.isSelected = !(weakSelf?.playButton?.isSelected)!;
        }
        tableHeaderView.addSubview(self.playButton!);
        
        
        let titleLable:STLabel = STLabel.init(frame: .init(x: SCREEN_WIDTH / 2 - 140, y: (self.playButton?.bottom)! + 20, width: SCREEN_WIDTH - 50, height: 17),
                                              text: self.model.nickname,
                                              textColor: FirstTextColor,
                                              font: 17,
                                              isSizetoFit: false,
                                              textAlignment: .right);
        
        titleLable.centerX = SCREEN_WIDTH / 2;
        titleLable.textAlignment = .center;
        tableHeaderView.addSubview(titleLable);
        
        

        
        
        
        
       let scanButton = STButton.init(frame: CGRect.init(x: SCREEN_WIDTH / 2 - 130, y: (titleLable.bottom) + 15, width: 110, height: 14),
                                        title: self.model.view_count,
                                        titleColor: ThirdTextColor,
                                        titleFont: 13,
                                        cornerRadius: 0,
                                        backgroundColor: .clear,
                                        backgroundImage: nil,
                                        image: UIImage.init(named: "btn_scan"));
        scanButton?.contentHorizontalAlignment = .right;
        
        scanButton?.titleEdgeInsets = .init(top: 0, left: 5, bottom: 0, right: 0);
        
        tableHeaderView.addSubview(scanButton!);
        
        let listenButton =  STButton.init(frame: CGRect.init(x: SCREEN_WIDTH / 2  + 20, y: 0, width: 70, height: 14),
                                          title: self.model.total_play_count,
                                          titleColor: SecendTextColor,
                                          titleFont: 13,
                                          cornerRadius: 0,
                                          backgroundColor: .clear,
                                          backgroundImage: nil,
                                          image: UIImage.init(named: "btn_listen"));
        listenButton?.contentHorizontalAlignment = .left;
        listenButton?.centerY = (scanButton?.centerY)!;
        tableHeaderView.addSubview(listenButton!);
        
        
        let desLable:STLabel = STLabel.init(frame: .init(x: 0, y: (listenButton?.bottom)! + 40, width: SCREEN_WIDTH - 50, height: 17),
                                              text: self.model.signature,
                                              textColor: ThirdTextColor,
                                              font: 14,
                                              isSizetoFit: false,
                                              textAlignment: .right);
        
        desLable.centerX = SCREEN_WIDTH / 2;
        desLable.textAlignment = .center;
        desLable.numberOfLines = 0;
        
        let str:NSString = NSString.init(string: model.signature!)
        desLable.height = str.heigthWithwidth(SCREEN_WIDTH - 50, font: 14);
        tableHeaderView.addSubview(desLable);
        
        
        let musicLable:STLabel = STLabel.init(frame: .init(x: 25, y: desLable.bottom + 40, width: 120, height: 17),
                                      text: " ▌音乐人.Music",
                                      textColor: FirstTextColor,
                                      font: 15,
                                      isSizetoFit: false,
                                      textAlignment: .left);
        
        musicLable.textAlignment = .left;
        tableHeaderView.addSubview(musicLable);

        let numLable:STLabel = STLabel.init(frame: .init(x: SCREEN_WIDTH - 25 - 120, y: desLable.bottom + 40, width: 120, height: 17),
                                              text: "全部" + self.model.track_count! + "首",
                                              textColor: ThirdTextColor,
                                              font: 13,
                                              isSizetoFit: false,
                                              textAlignment: .right);
        
        numLable.centerY  = musicLable.centerY;
        numLable.textAlignment = .right;
        tableHeaderView.addSubview(numLable);
        
        let line:UIView = UIView.init(frame: CGRect.init(x: 25, y: numLable.bottom + 2, width: SCREEN_WIDTH - 50, height: 1));
        line.backgroundColor = LINE_COLOR;
        line.centerX = SCREEN_WIDTH / 2;
        tableHeaderView.addSubview(line);
        
        tableHeaderView.height = line.bottom + 10;
        
        self.tableView.tableHeaderView = tableHeaderView;
        
        
    }

    // MARK: UITableView DataSouce
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1;
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSouce.count;
    }
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return YYFindMusicDetailTableViewCell.cellHeight;
    }
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.0001;
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell:YYFindMusicDetailTableViewCell? = tableView.dequeueReusableCell(withIdentifier: "cell") as? YYFindMusicDetailTableViewCell;
        if cell == nil {
            cell = YYFindMusicDetailTableViewCell.init(style: .default, reuseIdentifier: "cell");
        }
        
        let model:YYTrack = self.dataSouce[indexPath.row];
        
        model.indexString = String(indexPath.row + 1);
        cell?.selectionStyle = .none;
        cell?.model = model;
        return cell!;
    }
    
    // MARK: UITableView Delegate
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: false);
        let trackModel:YYTrack = self.dataSouce[indexPath.row];
        
        for oneModel in self.dataSouce {
            
            if oneModel.id != trackModel.id {
                oneModel.playType = .nomal;
            }
            
        }
        
        
        var type:YYTrackModelType = .nomal;
        if trackModel.playType == .nomal {
            type = .isPlaying;
        }else if trackModel.playType == .isPlaying {
            type = .pause;
        }else{
            type = .isPlaying;
        }
        trackModel.playType = type;
        
        self.tableView.reloadData();
        
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: NetWork
    func loadNetworkRequest() -> Void {
        let time:Int = Int(NSDate().timeIntervalSince1970);
        let str = "http://wawa.fm:9090/wawa/api.php/Musician/tracks_?uid=\((model.uid)!)&datatype=jsonp&r=100&page=1&type=0&callback=data&_=\(time)"
        YYYuYinNetWorkManger.defultManger.getNetwork(urlString: str, dic: [:], isJson: false
            , successHandle: { (json) in
            
            print("json = \(json)");
            var str = String.init(data: json as! Data, encoding: .utf8);
                
            let index = str?.index((str?.startIndex)!, offsetBy: 6);
            str = str?.substring(from: index!);
                
                
            str = str?.substring(to: (str?.index((str?.endIndex)!, offsetBy: -1))!);
                
                
            let data = str?.data(using: .utf8);
                
            let dic = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)
            
       
                if let array:Array<Dictionary<String,Any>> = dic as? Array{
                
                                for objectdic in array{
                    
                                        let model:YYTrack = YYTrack.mj_object(withKeyValues: objectdic);
                    
                                        self.dataSouce.append(model);
                                        
                                }
                
                }

                 self.loadPeopleInfoRequest();
               
            
//                self.isListUpdate = true;
//                if (self.isInfoUpdate == true) && (self.isListUpdate == true) {
//                 
//                    self.tableView?.reloadData();
//                    self.isListUpdate = false;
//                    self.isListUpdate = true;
//                }

          
            
            
        }) { (str) in

        };
    }
    

    func loadPeopleInfoRequest(){
        //获取音乐人详细信息，非json
        let time:Int = Int(NSDate().timeIntervalSince1970);
        let url = "http://wawa.fm:9090/wawa/api.php/Musician/info_?datatype=jsonp&uid=\((model.uid)!)&callback=data&_=\(time)";
        YYYuYinNetWorkManger.defultManger.getNetwork(urlString:url , dic: [:], isJson: false, successHandle: { (json) in
            
            var str = String.init(data: json as! Data, encoding: .utf8);
            
            let index = str?.index((str?.startIndex)!, offsetBy: 6);
            str = str?.substring(from: index!);
            
            
            str = str?.substring(to: (str?.index((str?.endIndex)!, offsetBy: -1))!);
            
            
            let data = str?.data(using: .utf8);
            
            let mydic = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)
            
            let model:YYMusicPeopleModel = YYMusicPeopleModel.mj_object(withKeyValues: mydic);
    
            self.model = model;

            self.configSubView();
            self.tableView.reloadData();
            
            
        }) { (failStr) in
            
        }
    
    }

}
